/**
 * 曲谱库
 */
// 调试日志保存 使用方法 logDebug(currentFile,,xxx,xxxx)  xxxx 不限制
const logDebug = require('../logs/log_debug'); // 日志工具
const {join} = require('path');  // 路径
const currentFile= join(__filename);    // 当前文件的路径 
const { mobuzDb } = require('../config');
const {analysisRequestMessage , compileResponseMessage } = require('../lib/buffer');

// 获取曲谱库数据
const obtainMusicScoreData = async (ctx) => {
    try {
        // 解密
        let msgReq = await analysisRequestMessage(__dirname+'/../proto/MusicScore.proto','MusicScore.MusicScoreReqMsg',ctx);
        logDebug(currentFile,msgReq,'.......msgReq')
        // 页码
        let page = msgReq['page'] || 1;
        // 一页几条，默认10条
        let size = msgReq['size'] || 10;
        // 获取曲谱数据 type ： 1吉他谱 2尤克里里  state：1热度 2最新
        const scoreData = await mobuzDb('edu_song_library as a')
                                    .where({'a.type': msgReq['type']  || null,'a.STATUS' : 1})
                                    .select('a.ID as id','a.NAME as name','a.SINGER as singer','a.SINGER_IMG as singerImg','a.HOT as hot','a.TAGS as tags','a.IMG as img','a.CREATE_TIME as createTime','a.STATUS as status','a.TYPE as type' ,'a.UPDATE_TIME as updateTime')
                                    .orderByRaw(`${msgReq['state'] === 1 ? 'a.HOT DESC': 'a.UPDATE_TIME DESC , a.CREATE_TIME DESC'}`)
                                    .limit(size).offset(Number(page-1) * size);
        // 获取总数
        const scoreDataTotal = await mobuzDb('edu_song_library as a')
                                    .where({'a.type': msgReq['type'] || null,'a.STATUS' : 1})
                                    .select('a.ID as id')
                                    .orderByRaw(`${msgReq['state'] === 1 ? 'a.HOT DESC': 'a.UPDATE_TIME DESC , a.CREATE_TIME DESC'}`)
                                    .count('a.id')
                                    .first();
        for (let i = 0; i < scoreData.length; i++) {
            scoreData[i]['createTime'] = await new Date(scoreData[i]['createTime']).getTime();
            
        };
        // 编译
        let msgRes = await compileResponseMessage(__dirname+'/../proto/MusicScore.proto','MusicScore.MusicScoreResMsg',{status: 200,msg: 'success',data: scoreData,total: scoreDataTotal['count(`a`.`id`)']})
        ctx.body = msgRes;
    } catch (e) {
        // 编译
        let msgRes = await compileResponseMessage(__dirname+'/../proto/MusicScore.proto','MusicScore.MusicScoreResMsg',{status: 500,msg: '前方堵塞，服务器繁忙'})
        ctx.body = msgRes;
    }
}
// 首页曲谱库
const obtainHomeMusicScoreData = async (ctx) => {
    const page = 1;
    const size = 10;
    try {
        // 获取曲谱数据 type ： 1吉他谱 2尤克里里  state：1热度 2最新
        // 吉他谱 热门
        const hotGuitar = await mobuzDb('edu_song_library as a')
                                .where({'a.type': 1,'a.STATUS' : 1})
                                .select('a.ID as id','a.NAME as name','a.SINGER as singer','a.SINGER_IMG as singerImg','a.HOT as hot','a.TAGS as tags','a.IMG as img','a.CREATE_TIME as createTime','a.STATUS as status','a.TYPE as type')
                                .orderBy('a.HOT','desc')
                                .limit(size).offset(Number(page-1) * size);
        // 吉他谱 最新                            
        const newGuitar = await mobuzDb('edu_song_library as a')
                                    .where({'a.type': 1,'a.STATUS' : 1})
                                    .select('a.ID as id','a.NAME as name','a.SINGER as singer','a.SINGER_IMG as singerImg','a.HOT as hot','a.TAGS as tags','a.IMG as img','a.CREATE_TIME as createTime','a.STATUS as status','a.TYPE as type')
                                    .orderBy('a.UPDATE_TIME', 'desc')
                                    .orderBy('a.CREATE_TIME', 'desc')
                                    .limit(size).offset(Number(page-1) * size);
        // 尤克里里 热门
        const hotUKulele = await mobuzDb('edu_song_library as a')
                                    .where({'a.type': 2,'a.STATUS' : 1})
                                    .select('a.ID as id','a.NAME as name','a.SINGER as singer','a.SINGER_IMG as singerImg','a.HOT as hot','a.TAGS as tags','a.IMG as img','a.CREATE_TIME as createTime','a.STATUS as status','a.TYPE as type','a.UPDATE_TIME as updateTime')
                                    .orderBy('a.HOT','desc')
                                    .limit(size).offset(Number(page-1) * size);
        // 尤克里里 最新
        const newUKulele = await mobuzDb('edu_song_library as a')
                                    .where({'a.type': 2,'a.STATUS' : 1})
                                    .select('a.ID as id','a.NAME as name','a.SINGER as singer','a.SINGER_IMG as singerImg','a.HOT as hot','a.TAGS as tags','a.IMG as img','a.CREATE_TIME as createTime','a.STATUS as status','a.TYPE as type','a.UPDATE_TIME as updateTime')
                                    .orderBy('a.UPDATE_TIME', 'desc')
                                    .orderBy('a.CREATE_TIME', 'desc')
                                    .limit(size).offset(Number(page-1) * size);
        for (let i = 0 ; i < hotGuitar.length; i++) {
            hotGuitar[i]['createTime'] = await new Date(hotGuitar[i]['createTime']).getTime();
        };
        for (let i = 0 ; i < newGuitar.length; i++) {
            newGuitar[i]['createTime'] = await new Date(newGuitar[i]['createTime']).getTime();
        };
        for (let i = 0 ; i < hotUKulele.length; i++) {
            hotUKulele[i]['createTime'] = await new Date(hotUKulele[i]['createTime']).getTime();
            hotUKulele[i]['createTime'] = await new Date(hotUKulele[i]['createTime']).getTime();
        };
        for (let i = 0 ; i < newUKulele.length; i++) {
            newUKulele[i]['createTime'] = await new Date(newUKulele[i]['createTime']).getTime();
            newUKulele[i]['createTime'] = await new Date(newUKulele[i]['createTime']).getTime();
        };
        let msgRes = await compileResponseMessage(__dirname+'/../proto/MusicScore.proto','MusicScore.HomeMusicScoreResMsg',{status: 200,msg: 'success',data: {hotGuitar,newGuitar , hotUKulele, newUKulele }});
        ctx.body = msgRes;
    } catch (e) { 
        // 编译
        let msgRes = await compileResponseMessage(__dirname+'/../proto/MusicScore.proto','MusicScore.MusicScoreResMsg',{status: 500,msg: '前方堵塞，服务器繁忙'});
        ctx.body = msgRes;
    }
}
// 获取本月热度top15
const obtainCurrentMonthHot = async (ctx) => {
    const page = 1;
    const size = 15;
    try {
        // 解密
        let msgReq = await analysisRequestMessage(__dirname+'/../proto/MusicScore.proto','MusicScore.MusicScoreReqMsg',ctx);
        // 吉他谱 最新                            
        const scoreData = await mobuzDb('edu_song_library as a')
                                    .where({'a.Type': msgReq['type'],'a.STATUS' : 1})
                                    .select('a.ID as id','a.NAME as name','a.SINGER as singer','a.HOT as hot','a.STATUS as status','a.TYPE as type','a.FRONT_MONTH_HOT as frontMonthHot')
                                    .orderBy('a.FRONT_MONTH_HOT', 'desc')
                                    .limit(size).offset(Number(page-1) * size);
        // 编译
        let msgRes = await compileResponseMessage(__dirname+'/../proto/MusicScore.proto','MusicScore.MusicScoreResMsg',{status: 200,msg: 'success',data: scoreData})
        ctx.body = msgRes;   
    } catch (e) { 
        // 编译
        let msgRes = await compileResponseMessage(__dirname+'/../proto/MusicScore.proto','MusicScore.MusicScoreResMsg',{status: 500,msg: '前方堵塞，服务器繁忙'});
        ctx.body = msgRes;
    }
     
}
// 获取曲谱库详情
const obtainMusicScoreDetails = async (ctx) => {
    // try {
        // 解密
        let msgReq = await analysisRequestMessage(__dirname+'/../proto/MusicScore.proto','MusicScore.MusicScoreDetailsReqMsg',ctx);
        logDebug(currentFile,msgReq,'获取曲谱库详情')
        // 吉他谱 最新                            
        const scoreData = await mobuzDb('edu_song_library as a')
                                    .where({'a.ID': msgReq['id'] - 0,'a.STATUS' : 1})
                                    .select('a.ID as id','a.NAME as name','a.SINGER as singer','a.SINGER_IMG as singerImg','a.HOT as hot','a.TAGS as tags','a.IMG as img','a.CREATE_TIME as createTime','a.STATUS as status','a.TYPE as type')
                                    .first();
        
        // 游览量增长  月度游览量增长
        await mobuzDb('edu_song_library as a').where({'a.ID': msgReq['id'] - 0}).increment('a.MONTH_HOT',1).increment('a.HOT',1);
        // 编译
        let msgRes = await compileResponseMessage(__dirname+'/../proto/MusicScore.proto','MusicScore.MusicScoreDetailsResMsg',{status: 200,msg: 'success',data: scoreData})
        ctx.body = msgRes;                              
    // } catch (e) { 
    //     // 编译
    //     let msgRes = await compileResponseMessage(__dirname+'/../proto/MusicScore.proto','MusicScore.MusicScoreResMsg',{status: 500,msg: '前方堵塞，服务器繁忙'});
    //     ctx.body = msgRes;
    // }
}

// 搜索 特定 曲谱数据 (模糊搜索 歌曲名 歌手)
const grabbleMusicScoreData = async (ctx, next) => {
    try {
        // 解密
        let msgReq = await analysisRequestMessage(__dirname+'/../proto/MusicScore.proto','MusicScore.SearchScoreReqMsg', ctx);
        logDebug(currentFile, msgReq,'.......搜索')
        // 页码
        let page = msgReq['page'] || 1;
        // 一页几条，默认10条
        let size = msgReq['size'] || 10;
        // 获取曲谱数据 type ： 1吉他谱 2尤克里里  state：1热度 2最新
        const scoreData = await mobuzDb('edu_song_library as a')
                                    .where({'a.type': msgReq['type']+'','a.STATUS' : 1})
                                    .andWhere('a.name', 'like', '%' + msgReq['text'] + '%').orWhere('a.singer', 'like', '%' + msgReq['text'] + '%')
                                    .select('a.ID as id','a.NAME as name','a.SINGER as singer','a.SINGER_IMG as singerImg','a.HOT as hot','a.TAGS as tags','a.IMG as img','a.CREATE_TIME as createTime','a.STATUS as status','a.TYPE as type' ,'a.UPDATE_TIME as updateTime')
                                    .orderByRaw(`${msgReq['state'] === 1 ? 'a.HOT DESC': 'a.UPDATE_TIME DESC , a.CREATE_TIME DESC'}`)
                                    .limit(size).offset(Number(page-1) * size);
        // 获取总数
        const scoreDataTotal = await mobuzDb('edu_song_library as a')
                                    .where({'a.type': msgReq['type']+'','a.STATUS' : 1})
                                    .andWhere('a.name', 'like', '%' + msgReq['text'] + '%').orWhere('a.singer', 'like', '%' + msgReq['text'] + '%')
                                    .select('a.ID as id')
                                    .orderByRaw(`${msgReq['state'] === 1 ? 'a.HOT DESC': 'a.UPDATE_TIME DESC , a.CREATE_TIME DESC'}`)
                                    .count('a.id')
                                    .first();
        for (let i = 0; i < scoreData.length; i++) {
            scoreData[i]['createTime'] = await new Date(scoreData[i]['createTime']).getTime();
            
        };
        // 编译
        let msgRes = await compileResponseMessage(__dirname+'/../proto/MusicScore.proto','MusicScore.MusicScoreResMsg',{status: 200,msg: 'success',data: scoreData,total: scoreDataTotal['count(`a`.`id`)']})
        ctx.body = msgRes;
    } catch (e) {
        // 编译
        let msgRes = await compileResponseMessage(__dirname+'/../proto/MusicScore.proto','MusicScore.MusicScoreResMsg',{status: 500,msg: '前方堵塞，服务器繁忙'})
        ctx.body = msgRes;
    }
}

module.exports = {
    obtainMusicScoreData,
    obtainHomeMusicScoreData,
    obtainCurrentMonthHot,
    obtainMusicScoreDetails,
    grabbleMusicScoreData
}